<?php

class InvoiceLedgerController extends Controller {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/customer';

    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            array(
                'application.filters.RequireLoginFilter',
            ),
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions

                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate($invoice) {
        /*
          $jsonData = json_decode($_REQUEST['data'], true);
          foreach ($jsonData as $item) {
          $model = new InvoiceLedger;
          $model->attributes = $item;
          $model->description = $item['description'];
          $model->invoice = $_GET['invoice'];
          $inventotyModel = Inventory::model()->find('partno=:partno', array(
          'partno' => $model->partno));
          $subcat = Invsubcategories::model()->find('subcategory=:subcat', array(
          'subcat' => $inventotyModel->subcat));
          if ($subcat->applymarkup == 'Average Cost')
          $model->cost =  $inventotyModel->averagecost;
          else
          $model->cost =   $inventotyModel->baseprice;
          $model->scredit = $inventotyModel->salescredit;
          $model->sdebit = $inventotyModel->salesdebit;
          $model->cdebit = $inventotyModel->costcredit;
          $model->ccredit = $inventotyModel->costdebit;
          $model->status=1;
          if ($model->save())
          echo 'itemAdded';
          }
         */
        $model = new InvoiceLedger;
        $model->invoice = $invoice;
        $model->noprint = 0;
        $model->taxed = 0;
        $model->status = 2;
        if ($model->save()) {
            echo "save successfull";
        }
    }

    public function actionSaveBatch() {
       
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id=NULL) {
        if ($id != 0) {
            $model = $this->loadModel($id);

            $model->attributes = $_REQUEST;
            if ($model->status == 2) {
                $model->status = 1;
            }
            if (isset($_REQUEST['description']))
                $model->description = $_REQUEST['description'];

            if ($model->save())
                echo 'Update succes';
        }elseif ($id == 0) {
            $model = new InvoiceLedger;
            $model->attributes = $_REQUEST;
            $model->id = NULL;
            $model->status = 1;
            if ($model->save()) {
                echo 'Add successful';
            } else {
                echo json_encode($model->getErrors());
            }
        }
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
      
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $model = InvoiceLedger::model()->findByPk($id);
        
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    public function actionGetInvoiceItems($invoice, $page=0, $sort=NULL) {

        if ($page > 0)
            $page--;
        $order = CJSON::decode($sort);
        $items = new CActiveDataProvider('InvoiceLedger', array(
                    'criteria' => array(
                        'condition' => "invoice=:invoice AND status!=2",
                        'params' => array(
                            'invoice' => $invoice
                        ),
                        'order' => isset($sort) ? $order[0]['property'] . ' ' . $order[0]['direction'] : NULL,
                    ),
                    'pagination' => array(
                        'pageSize' => 20,
                        'currentPage' => $page,
                    ),
                ));

        $itemsList = array();
        if ($items->getTotalItemCount() > 0) {
            $itemsList['totalCount'] = $items->getTotalItemCount();
            $itemsList['type'] = 'Items';
            foreach ($items->getData() as $i => $item) {
                $itemsList['data'][$i] = $item->getAttributes();
                $itemsList['data'][$i]['noprinttext'] = $item->getYesNoValue($item->noprint);
                $itemsList['data'][$i]['taxedtext'] = $item->getYesNoValue($item->taxed);
            }
            echo json_encode($itemsList);
        }
        Yii::app()->end();
    }

    public function actionGetItemsCost() {
        $totalCost = 0;
        $jsonData = json_decode($_REQUEST['data'], true);

        foreach ($jsonData as $item) {
            $model = Inventory::model()->find('partno=:partno', array(
                'partno' => $item['partno']));

            // echo $model->description;
            if ($model != NULL) {

                $totalCost+=$model->getCost();
            }
        }

        echo number_format($totalCost, 2, '.', '');
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'invoice-ledger-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

}
